package com.xy.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xxy
 * @date 2022/1/7 16:07
 */
@Slf4j
@RestController
@RequestMapping("use-redis-dcs-lock-01")
public class UseRedisDCSLock01 {

    private final StringRedisTemplate redisTemplate;

    public UseRedisDCSLock01(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("test-use-redis-dcs-lock")
    public Object testUseRedisDCSLock() {
        // 先抢占锁 原子操作
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "123", 10, TimeUnit.SECONDS);
        if (lock){
            try {
                // 抢占成功，执行业务
                List<String> dbList = dataList();
                return dbList;
            } finally {
                redisTemplate.delete("lock");
            }
        } else {
            try {
                // 抢占锁失败，等待一会
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 递归调用 可能导致栈内存溢出
            return testUseRedisDCSLock();
        }
    }


    private List<String> dataList() {
        List<String> dataList = new ArrayList<>();
        String[] data = {"a", "b", "c"};
        List<String> list = Arrays.asList(data);
        dataList.addAll(list);
        return dataList;
    }


}
